# coding=utf-8
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.shortcuts import render_to_response
from django.template.context import Context, RequestContext
from mongoutils.mongoutils import MongoHelper

mongoUtil=MongoHelper()
ADDS_FOR_PAGE = 5
filters = {'tags':'Palabra','cat':'Categoria','zones.desc':'Zona','szones.desc':'Sub Zona','date':'Periodo'}

def index(request):
    docs = mongoUtil.findLastAdJob()
    return populateIndex(request, docs)


def find(request,expr):
    '''for key in dictionary.keys():
        bread = None
        if len(breadcrumbs) >1:
            bread = breadcrumbs[len(breadcrumbs)-1]
        breadcrumbs.append(Breadcrumb(filters[key],dictionary[key],bread))
    dictionary.update({'breadcrumbs':breadcrumbs})
    for bread in breadcrumbs:
        print bread
    '''
    dictionary = {}
    #breadcrumbs = []
    first_split = expr.split('__')
    for key_value in first_split:
        second_split = key_value.split('_')
        dictionary[second_split[0]]= second_split[1].decode('utf-8')
    docs = mongoUtil.findBy(dictionary)
    #dictionary.update({'breadcrumbs':MapperUrl().createBreadcrumbs(dictionary)})
    return populateIndex(request, docs,dictionary)

def populateIndex(request,docs,dictionary=None):
    items = list()
    def abbreviation(content):
        if len(content) < 200: 
            return content  
        else: 
            return content[:200]
    for doc in docs:
        jsonDoc={"id": doc['_id'],
                 "title": doc['title'],
                 "url": doc['url'], 
                 "abbreviate_text":abbreviation(doc['content']),
                 "full_text":doc['content'],
                 "category":doc['category'],
                 "provider":doc['provider'],
                 "creation_date": doc['creation_date']}
        items.append(jsonDoc)
    adds = createPaginator(request, items)
    categories = mongoUtil.findCategories(dictionary)
    dates = mongoUtil.findDates(dictionary)
    zones = mongoUtil.findZones(dictionary)
    subZones= mongoUtil.findSubZones(dictionary)
    contextDict = {
        'items': adds,
        'categories' : categories,
        'dates' :dates,
        'zones' : zones,
        'sub_zones' : subZones,
        'totalAdds' : docs.count(),
        'selected_zone':None,
        'selected_szone':None,
    }
    if dictionary is not None:
        if dictionary.has_key('zones.desc'):
            dictionary.update({'selected_zone':True})
        if dictionary.has_key('tags'):
            dictionary.update({'word_key':dictionary['tags']["$all"][0]})
        if dictionary.has_key('szones.desc'):
            dictionary.update({'selected_szone':True})
        contextDict.update(dictionary)
    context = Context(contextDict)
    return render_to_response('index.html', context, context_instance=RequestContext(request))

def createPaginator(request,items):
    paginator = Paginator(items, ADDS_FOR_PAGE)
    page = request.GET.get('page')
    try:
        adds = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        adds = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        adds = paginator.page(paginator.num_pages)
    return adds
    
